package com.pod5.skype.parser;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.util.LinkedList;

public class CrawledIPState {

	private File rawIPDataFile;
	private File readableIPFile;
	private File crawledIPFile;
	
	CrawledIPState(){
		rawIPDataFile = new File("rawIPDataFile");
		 readableIPFile = new File("readableIPFile");
		 crawledIPFile = new File("crawledIPFile");
	}
	
	public LinkedList<String> loadState(String dataType) throws DataTypeException{
		LinkedList<String> list = new LinkedList<String>();
		File file = null;
		if(dataType == "rawIPData")
			file = rawIPDataFile;
		else if(dataType == "readableIP")
			file = readableIPFile;
		else if(dataType == "crawledIP")
			file = crawledIPFile;
		else
			throw new DataTypeException();
		
		try{
			 BufferedReader input =  new BufferedReader(new FileReader(file));
			try{
		        String line = null; //not declared within while loop

		        while (( line = input.readLine()) != null){
		        	line = line.trim();
		        	if(!line.isEmpty())
		        		list.add(line);
		        }
		        
		
			}
			 finally {
				 input.close();
		     }
		 }
	   catch (IOException ex){
	     ex.printStackTrace();
	   }
		
		return list;
	}
	
	public void saveState(LinkedList<String> list, String dataType) throws DataTypeException{
		File file = null;
		if(dataType == "rawIPData")
			file = rawIPDataFile;
		else if(dataType == "readableIP")
			file = readableIPFile;
		else if(dataType == "crawledIP")
			file = crawledIPFile;
		else
			throw new DataTypeException();
		
		try {
			Writer output = new BufferedWriter(new FileWriter(file));

		    try {
		      //FileWriter always assumes default encoding is OK!
			    for(int i1 = 0; i1<list.size(); i1++)
			    {
			    	output.write( list.get(i1) + "\r\n");
			    }
			    
		    }
		    finally {
		    	output.close();
		    }
		    } 
		    catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
	}
	
}
